<?php
$list = new stdClass;
$output = '';

function sortObjectByKey($obj,$order=''){
	$tmp = array();
	foreach($obj as $key => $val){
		if(is_object($val)){
			$parts = explode('_', $key);
			$tmp[$parts[0]] = $parts[1];
		}else{
			$tmp[$key] = '';
		}
	}

	if($order == 'DESC'){
		krsort($tmp);
	} else {
		ksort($tmp);
	}

	$tmpObj = new stdClass();
	foreach($tmp as $key => $val){
		if($val !== ''){
			$key = $key.'_'.$val;
			$tmpObj->$val = $obj->$key;
		}else{
			$tmpObj->$key = $obj->$key;
		}
	}
	return $tmpObj;
}

function print_obj($obj, $CFG){
	$obj = sortObjectByKey($obj, 'ASC');
	global $output;
	foreach($obj as $key => $value){
		$output .= '<div style="margin-bottom:10px;">';
		if(is_object($value)){
			if($cat = get_record('course_categories', 'id', $key)){
				$output .= '<a href="#" onclick="showHide(\'cat_'.$cat->id.'\', \''.$CFG->wwwroot.'\');return false;"><img src="'.$CFG->wwwroot.'/blocks/cat_course_list/up.png" id="cat_'.$cat->id.'_icon" /> <span style="font-weight:bold;">'.$cat->name.'</span></a>';
				$output .= '<div id="cat_'.$cat->id.'" style="display:none;padding-left:10px;">';
			}else{
				echo "Error<br />";
			}
			print_obj($value, $CFG);
		}else{
			if($course = get_record('course', 'id', $key)){
				if(!$course->visible){
					$color = ' color:gray;';
				}else{
					$color = '';
				}
				$output .= '<div style="margin:2px; padding:2px; border-bottom:1px dotted black;'.$color.'"><a style="'.$color.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'" title="'.$course->shortname.'">'.$course->fullname.'</a></div>';
			}
		}
		$output .= '</div>';
	}
	$output .= '</div>';
	return $output;
}

function cat_order($cat, $courses){
	global $list;
	$temp_array = array();
	while(intval($cat)){
		if($current_cat = get_record('course_categories', 'id', $cat)){
			array_unshift($temp_array, $current_cat);
			$cat = $current_cat->parent;
		}
	}
	$r =& $list;
	foreach($temp_array as $value){
		if($value->sortorder == 999){
			$key = $value->id.'_'.$value->id;
		}else{
			$key = $value->sortorder.'_'.$value->id;
		}
		if(!isset($r->$key)){
			$r->$key = new stdClass;
		}
		$r =& $r->$key;
	}
	foreach($courses as $key => $value){
		$r->$key = $value;
	}
}

function new_build_cat($rs, $CFG){
	global $list;
	$cats = new stdClass;
	foreach($rs as $r){
		$cat = $r->category;
		$rid = $r->id;
		$cats->$cat->$rid = $r->shortname;
	}
	foreach($cats as $key => $cat){
		cat_order($key, $cat);
	}
	$output = print_obj($list, $CFG);
	return $output;
}

?>
